package com.kaifamiao.thread.d0927;

public class Test01 {

    public static void main(String[] args) {
        Num num = new Num();

        Runnable plus = () ->{
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                num.plus();
            }
        };
        Runnable minus = () -> {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                num.minus();
            }
        };

        Thread p1 = new Thread(plus, "plu1");
        Thread p2 = new Thread(plus, "plu2");

        Thread m1 = new Thread(minus, "minus1");
        Thread m2 = new Thread(minus, "minus2");

        p1.start();
        p2.start();
        m1.start();
        m2.start();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(num.j);
    }
}


class Num {

    public int j = 0;


    public synchronized void plus(){
        System.out.println(Thread.currentThread().getName() +" 对 j 加一 后是：" + ++ j);
    }

    public synchronized void minus(){
        System.out.println(Thread.currentThread().getName() + "对 j 减一后是：" + -- j );
    }
}
